--障碍块
require "app.models.Common"

local Block = class("Block")

function Block:ctor(node)
	self.node = node
end

--设置图片
function Block:Set(index)
	if nil ~= self.sp then
		self.node:removeChild(self.sp)
	end

	self.index = index
	self.sp = display.newSprite(string.format("block%d.png", index))
	self.node:addChild(self.sp)
	local rawSize = self.sp:getContentSize()
	self.size = rawSize.width / cGridSize * display.contentScaleFactor
end

--设置位置
function Block:SetPos(x, y)
	--防止方块放到屏幕外
	local bound = cBound - 1
	x = math.max(x, -bound)
	x = math.min(x, bound - self.size + 1)

	y = math.max(y, -bound)
	y = math.min(y, bound - self.size + 1)

	local posx, posy = Grid2Pos(x, y)
	local rawSize = self.sp:getContentSize()
	--摆位置不是以图片的中心，而是以图片的左下角来拜访，所以要进行下面的换算
	self.sp:setPosition(posx + rawSize.width / 2  - cGridSize / 2,
						posy + rawSize.height / 2  - cGridSize / 2)

	self.x, self.y = x, y
end

--设置碰撞
function Block:SetBlock( )
	for bx = 0, self.size - 1 do
		for by = 0, self.size - 1 do
			cc.exports.SetCollide(self.x + bx, self.y + by, { Type = "block" })
		end
	end
end

local function AxisHit(a, asize, b, bsize)
	if a < b then
		return a + asize > b
	else
		return b + bsize > a
	end
end

function Block:Hit(b)
	return AxisHit(self.x, self.size, b.x, b.size) and AxisHit(self.y, self.size, b.y, b.size)
end

function Block:Clear( )
	self.node:removeChild(self.sp)
end

return Block